package xyz.luckyli.myrule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;

/**
 * ClassName:myrule
 * Package:xyz.luckyli.myrule
 * Description:
 *
 * @Date:2020/11/2 21:07
 * @Author:857251389@qq.com
 */

public class LxxRandomRule extends AbstractLoadBalancerRule {

    //计数
    private int total = 0;

    //当前服务
    private int currentIndex = 0;


    @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while (server == null) {
                if (Thread.interrupted()) {
                    return null;
                }

                //获取活着的服务
                List<Server> upList = lb.getReachableServers();
                //获取所有服务
                List<Server> allList = lb.getAllServers();
                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }

                if(total < 3){
                    total++;
                    server = upList.get(currentIndex);
                }else{
                    currentIndex++;
                    total = 0;
                    if(currentIndex >= upList.size()){
                        currentIndex = 0;
                    }
                    server = upList.get(currentIndex);
                }


                if (server == null) {
                    /*
                     * The only time this should happen is if the server list were
                     * somehow trimmed. This is a transient condition. Retry after
                     * yielding.
                     */
                    Thread.yield();
                    continue;
                }

                if (server.isAlive()) {
                    return (server);
                }

            }

            return server;
        }
    }

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
        
    }

    @Override
    public Server choose(Object o) {
        return null;
    }
}